import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Alert,
  Tooltip,
  Menu,
  ListItemIcon,
  ListItemText,
  Divider,
  CircularProgress,
} from '@mui/material';
import {
  Add as AddIcon,
  PlayArrow as StartIcon,
  Stop as StopIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  MoreVert as MoreIcon,
  Refresh as RefreshIcon,
  Info as InfoIcon,
  Warning as WarningIcon,
  CheckCircle as SuccessIcon,
  Error as ErrorIcon,
  FileCopy as CopyIcon,
} from '@mui/icons-material';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import toast from 'react-hot-toast';

// Store
import { useAppStore } from '../store/appStore';

// Types
import type { Tunnel, TunnelConfig, TunnelType, TunnelStatus } from '../types/ssh';

interface TunnelFormData {
  name: string;
  connection_id: string;
  tunnel_type: TunnelType;
  local_host: string;
  local_port: number;
  remote_host: string;
  remote_port: number;
  description?: string;
}

const TunnelManager: React.FC = () => {
  const {
    connections,
    activeConnections,
    tunnels,
    addTunnel,
    updateTunnel,
    removeTunnel,
  } = useAppStore();

  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [selectedTunnel, setSelectedTunnel] = useState<Tunnel | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [menuTunnel, setMenuTunnel] = useState<Tunnel | null>(null);
  const [formData, setFormData] = useState<TunnelFormData>({
    name: '',
    connection_id: '',
    tunnel_type: 'local',
    local_host: 'localhost',
    local_port: 8080,
    remote_host: 'localhost',
    remote_port: 80,
    description: '',
  });

  // 获取隧道状态图标和颜色
  const getTunnelStatusInfo = (status: TunnelStatus) => {
    switch (status.status) {
      case 'active':
        return { icon: <SuccessIcon />, color: 'success' as const, text: '活动' };
      case 'starting':
        return { icon: <CircularProgress size={16} />, color: 'info' as const, text: '启动中' };
      case 'stopping':
        return { icon: <CircularProgress size={16} />, color: 'warning' as const, text: '停止中' };
      case 'stopped':
        return { icon: <StopIcon />, color: 'default' as const, text: '已停止' };
      case 'error':
        return { icon: <ErrorIcon />, color: 'error' as const, text: '错误' };
      default:
        return { icon: <InfoIcon />, color: 'default' as const, text: '未知' };
    }
  };

  // 获取隧道类型显示文本
  const getTunnelTypeText = (type: TunnelType) => {
    switch (type) {
      case 'local':
        return '本地转发';
      case 'remote':
        return '远程转发';
      case 'dynamic':
        return '动态转发';
      default:
        return type;
    }
  };

  // 创建隧道
  const createTunnel = async () => {
    if (!formData.name || !formData.connection_id) {
      toast.error('请填写必要信息');
      return;
    }

    setIsLoading(true);
    try {
      const tunnelConfig: TunnelConfig = {
        tunnel_type: formData.tunnel_type,
        local_host: formData.local_host,
        local_port: formData.local_port,
        remote_host: formData.remote_host,
        remote_port: formData.remote_port,
      };

      const tunnelId = await invoke('create_tunnel', {
        connectionId: formData.connection_id,
        config: tunnelConfig,
      });

      const newTunnel: Tunnel = {
        id: tunnelId as string,
        connection_id: formData.connection_id,
        name: formData.name,
        config: tunnelConfig,
        status: { status: 'stopped' },
        description: formData.description,
        created_at: new Date().toISOString(),
      };

      addTunnel(newTunnel);
      setIsCreateDialogOpen(false);
      resetForm();
      toast.success('隧道已创建');
    } catch (error) {
      console.error('Failed to create tunnel:', error);
      toast.error('创建隧道失败: ' + (error as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  // 启动隧道
  const startTunnel = async (tunnel: Tunnel) => {
    try {
      updateTunnel(tunnel.id, { status: { status: 'starting' } });
      
      await invoke('start_tunnel', { tunnelId: tunnel.id });
      
      updateTunnel(tunnel.id, { status: { status: 'active' } });
      toast.success(`隧道 "${tunnel.name}" 已启动`);
    } catch (error) {
      console.error('Failed to start tunnel:', error);
      updateTunnel(tunnel.id, { 
        status: { 
          status: 'error', 
          error: (error as Error).message 
        } 
      });
      toast.error('启动隧道失败: ' + (error as Error).message);
    }
  };

  // 停止隧道
  const stopTunnel = async (tunnel: Tunnel) => {
    try {
      updateTunnel(tunnel.id, { status: { status: 'stopping' } });
      
      await invoke('stop_tunnel', { tunnelId: tunnel.id });
      
      updateTunnel(tunnel.id, { status: { status: 'stopped' } });
      toast.success(`隧道 "${tunnel.name}" 已停止`);
    } catch (error) {
      console.error('Failed to stop tunnel:', error);
      updateTunnel(tunnel.id, { 
        status: { 
          status: 'error', 
          error: (error as Error).message 
        } 
      });
      toast.error('停止隧道失败: ' + (error as Error).message);
    }
  };

  // 删除隧道
  const deleteTunnel = async (tunnel: Tunnel) => {
    try {
      // 如果隧道正在运行，先停止它
      if (tunnel.status.status === 'active') {
        await stopTunnel(tunnel);
      }

      await invoke('delete_tunnel', { tunnelId: tunnel.id });
      removeTunnel(tunnel.id);
      toast.success(`隧道 "${tunnel.name}" 已删除`);
    } catch (error) {
      console.error('Failed to delete tunnel:', error);
      toast.error('删除隧道失败: ' + (error as Error).message);
    }
  };

  // 复制隧道信息到剪贴板
  const copyTunnelInfo = (tunnel: Tunnel) => {
    const info = `隧道: ${tunnel.name}\n类型: ${getTunnelTypeText(tunnel.config.tunnel_type)}\n本地: ${tunnel.config.local_host}:${tunnel.config.local_port}\n远程: ${tunnel.config.remote_host}:${tunnel.config.remote_port}`;
    navigator.clipboard.writeText(info);
    toast.success('隧道信息已复制到剪贴板');
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      name: '',
      connection_id: '',
      tunnel_type: 'local',
      local_host: 'localhost',
      local_port: 8080,
      remote_host: 'localhost',
      remote_port: 80,
      description: '',
    });
  };

  // 打开编辑对话框
  const openEditDialog = (tunnel: Tunnel) => {
    setSelectedTunnel(tunnel);
    setFormData({
      name: tunnel.name,
      connection_id: tunnel.connection_id,
      tunnel_type: tunnel.config.tunnel_type,
      local_host: tunnel.config.local_host,
      local_port: tunnel.config.local_port,
      remote_host: tunnel.config.remote_host,
      remote_port: tunnel.config.remote_port,
      description: tunnel.description || '',
    });
    setIsEditDialogOpen(true);
  };

  // 更新隧道
  const updateTunnelConfig = async () => {
    if (!selectedTunnel || !formData.name) {
      toast.error('请填写必要信息');
      return;
    }

    setIsLoading(true);
    try {
      const updatedTunnel: Partial<Tunnel> = {
        name: formData.name,
        description: formData.description,
        config: {
          tunnel_type: formData.tunnel_type,
          local_host: formData.local_host,
          local_port: formData.local_port,
          remote_host: formData.remote_host,
          remote_port: formData.remote_port,
        },
      };

      await invoke('update_tunnel', {
        tunnelId: selectedTunnel.id,
        config: updatedTunnel.config,
      });

      updateTunnel(selectedTunnel.id, updatedTunnel);
      setIsEditDialogOpen(false);
      setSelectedTunnel(null);
      resetForm();
      toast.success('隧道已更新');
    } catch (error) {
      console.error('Failed to update tunnel:', error);
      toast.error('更新隧道失败: ' + (error as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  // 监听隧道状态变化
  useEffect(() => {
    const unlisten = listen('tunnel-status-changed', (event: any) => {
      const { tunnel_id, status } = event.payload;
      updateTunnel(tunnel_id, { status });
    });

    return () => {
      unlisten.then(fn => fn());
    };
  }, [updateTunnel]);

  // 获取可用的连接列表（已连接的）
  const availableConnections = connections.filter(conn => 
    activeConnections.some(ac => ac.id === conn.id && ac.status.status === 'connected')
  );

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 隧道管理头部 */}
      <Paper sx={{ mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', p: 2 }}>
          <Typography variant="h5">
            隧道管理
          </Typography>
          
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={<RefreshIcon />}
              onClick={() => {
                // 刷新隧道状态
                tunnels.forEach(tunnel => {
                  invoke('get_tunnel_status', { tunnelId: tunnel.id })
                    .then((status) => {
                      updateTunnel(tunnel.id, { status: status as TunnelStatus });
                    })
                    .catch(console.error);
                });
              }}
            >
              刷新
            </Button>
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => {
                resetForm();
                setIsCreateDialogOpen(true);
              }}
              disabled={availableConnections.length === 0}
            >
              新建隧道
            </Button>
          </Box>
        </Box>
      </Paper>

      {/* 隧道列表 */}
      <Paper sx={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        {availableConnections.length === 0 ? (
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Alert severity="info">
              没有可用的连接。请先在连接管理页面建立SSH连接。
            </Alert>
          </Box>
        ) : tunnels.length === 0 ? (
          <Box sx={{ p: 3, textAlign: 'center' }}>
            <Typography variant="h6" gutterBottom>
              还没有创建任何隧道
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              点击上方的"新建隧道"按钮来创建您的第一个SSH隧道
            </Typography>
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => {
                resetForm();
                setIsCreateDialogOpen(true);
              }}
            >
              新建隧道
            </Button>
          </Box>
        ) : (
          <TableContainer sx={{ flex: 1 }}>
            <Table stickyHeader>
              <TableHead>
                <TableRow>
                  <TableCell>名称</TableCell>
                  <TableCell>连接</TableCell>
                  <TableCell>类型</TableCell>
                  <TableCell>本地地址</TableCell>
                  <TableCell>远程地址</TableCell>
                  <TableCell>状态</TableCell>
                  <TableCell>操作</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {tunnels.map((tunnel) => {
                  const connection = connections.find(c => c.id === tunnel.connection_id);
                  const statusInfo = getTunnelStatusInfo(tunnel.status);
                  
                  return (
                    <TableRow key={tunnel.id} hover>
                      <TableCell>
                        <Box>
                          <Typography variant="body2" fontWeight="medium">
                            {tunnel.name}
                          </Typography>
                          {tunnel.description && (
                            <Typography variant="caption" color="text.secondary">
                              {tunnel.description}
                            </Typography>
                          )}
                        </Box>
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2">
                          {connection?.name || '未知连接'}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={getTunnelTypeText(tunnel.config.tunnel_type)}
                          size="small"
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2" fontFamily="monospace">
                          {tunnel.config.local_host}:{tunnel.config.local_port}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="body2" fontFamily="monospace">
                          {tunnel.config.remote_host}:{tunnel.config.remote_port}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip
                          icon={statusInfo.icon}
                          label={statusInfo.text}
                          color={statusInfo.color}
                          size="small"
                        />
                        {tunnel.status.error && (
                          <Tooltip title={tunnel.status.error}>
                            <WarningIcon color="error" sx={{ ml: 1, fontSize: 16 }} />
                          </Tooltip>
                        )}
                      </TableCell>
                      <TableCell>
                        <Box sx={{ display: 'flex', gap: 0.5 }}>
                          {tunnel.status.status === 'active' ? (
                            <Tooltip title="停止隧道">
                              <IconButton
                                size="small"
                                onClick={() => stopTunnel(tunnel)}
                                color="error"
                              >
                                <StopIcon />
                              </IconButton>
                            </Tooltip>
                          ) : (
                            <Tooltip title="启动隧道">
                              <IconButton
                                size="small"
                                onClick={() => startTunnel(tunnel)}
                                color="success"
                                disabled={tunnel.status.status === 'starting' || tunnel.status.status === 'stopping'}
                              >
                                <StartIcon />
                              </IconButton>
                            </Tooltip>
                          )}
                          
                          <Tooltip title="更多操作">
                            <IconButton
                              size="small"
                              onClick={(e) => {
                                setAnchorEl(e.currentTarget);
                                setMenuTunnel(tunnel);
                              }}
                            >
                              <MoreIcon />
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Paper>

      {/* 操作菜单 */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={() => {
          setAnchorEl(null);
          setMenuTunnel(null);
        }}
      >
        <MenuItem onClick={() => {
          if (menuTunnel) {
            openEditDialog(menuTunnel);
          }
          setAnchorEl(null);
        }}>
          <ListItemIcon>
            <EditIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>编辑</ListItemText>
        </MenuItem>
        
        <MenuItem onClick={() => {
          if (menuTunnel) {
            copyTunnelInfo(menuTunnel);
          }
          setAnchorEl(null);
        }}>
          <ListItemIcon>
            <CopyIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>复制信息</ListItemText>
        </MenuItem>
        
        <Divider />
        
        <MenuItem 
          onClick={() => {
            if (menuTunnel) {
              deleteTunnel(menuTunnel);
            }
            setAnchorEl(null);
          }}
          sx={{ color: 'error.main' }}
        >
          <ListItemIcon>
            <DeleteIcon fontSize="small" color="error" />
          </ListItemIcon>
          <ListItemText>删除</ListItemText>
        </MenuItem>
      </Menu>

      {/* 创建隧道对话框 */}
      <Dialog
        open={isCreateDialogOpen}
        onClose={() => setIsCreateDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>创建新隧道</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="隧道名称"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                required
              />
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <FormControl fullWidth required>
                <InputLabel>选择连接</InputLabel>
                <Select
                  value={formData.connection_id}
                  label="选择连接"
                  onChange={(e) => setFormData({ ...formData, connection_id: e.target.value })}
                >
                  {availableConnections.map((conn) => (
                    <MenuItem key={conn.id} value={conn.id}>
                      {conn.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>隧道类型</InputLabel>
                <Select
                  value={formData.tunnel_type}
                  label="隧道类型"
                  onChange={(e) => setFormData({ ...formData, tunnel_type: e.target.value as TunnelType })}
                >
                  <MenuItem value="local">本地转发 (Local)</MenuItem>
                  <MenuItem value="remote">远程转发 (Remote)</MenuItem>
                  <MenuItem value="dynamic">动态转发 (SOCKS)</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="本地主机"
                value={formData.local_host}
                onChange={(e) => setFormData({ ...formData, local_host: e.target.value })}
              />
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="本地端口"
                type="number"
                value={formData.local_port}
                onChange={(e) => setFormData({ ...formData, local_port: parseInt(e.target.value) || 0 })}
              />
            </Grid>
            
            {formData.tunnel_type !== 'dynamic' && (
              <>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="远程主机"
                    value={formData.remote_host}
                    onChange={(e) => setFormData({ ...formData, remote_host: e.target.value })}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="远程端口"
                    type="number"
                    value={formData.remote_port}
                    onChange={(e) => setFormData({ ...formData, remote_port: parseInt(e.target.value) || 0 })}
                  />
                </Grid>
              </>
            )}
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="描述（可选）"
                multiline
                rows={2}
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setIsCreateDialogOpen(false)}>取消</Button>
          <Button onClick={createTunnel} variant="contained" disabled={isLoading}>
            创建
          </Button>
        </DialogActions>
      </Dialog>

      {/* 编辑隧道对话框 */}
      <Dialog
        open={isEditDialogOpen}
        onClose={() => setIsEditDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>编辑隧道</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="隧道名称"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                required
              />
            </Grid>
            
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>隧道类型</InputLabel>
                <Select
                  value={formData.tunnel_type}
                  label="隧道类型"
                  onChange={(e) => setFormData({ ...formData, tunnel_type: e.target.value as TunnelType })}
                >
                  <MenuItem value="local">本地转发 (Local)</MenuItem>
                  <MenuItem value="remote">远程转发 (Remote)</MenuItem>
                  <MenuItem value="dynamic">动态转发 (SOCKS)</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="本地主机"
                value={formData.local_host}
                onChange={(e) => setFormData({ ...formData, local_host: e.target.value })}
              />
            </Grid>
            
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="本地端口"
                type="number"
                value={formData.local_port}
                onChange={(e) => setFormData({ ...formData, local_port: parseInt(e.target.value) || 0 })}
              />
            </Grid>
            
            {formData.tunnel_type !== 'dynamic' && (
              <>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="远程主机"
                    value={formData.remote_host}
                    onChange={(e) => setFormData({ ...formData, remote_host: e.target.value })}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="远程端口"
                    type="number"
                    value={formData.remote_port}
                    onChange={(e) => setFormData({ ...formData, remote_port: parseInt(e.target.value) || 0 })}
                  />
                </Grid>
              </>
            )}
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="描述（可选）"
                multiline
                rows={2}
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setIsEditDialogOpen(false)}>取消</Button>
          <Button onClick={updateTunnelConfig} variant="contained" disabled={isLoading}>
            更新
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default TunnelManager;